package net.mygwt.ui.client.widget.table;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;

import net.mygwt.ui.client.Style;
import net.mygwt.ui.client.event.BaseEvent;
import net.mygwt.ui.client.widget.Component;



/**
 * @author simon
 * 
//Create just like normal table (style, columnmodel)
new EditTable(Style.MULTI | Style.HORIZONTAL, cm);

//Create an item for the table - don't use TableItem, use EditTableItem	
EditTableItem item = new EditTableItem(values); 

//default editor setup is a TextBox, can set your own
((EditTable)getTable()).setEditor(i, editorWidget);

//edit current Selection : 
((EditTable)getTable()).editCurrentRow();

//use finishEdit to close any editors and commit values back to table (see also commitEdit)
//use cancelEdit to return to pre=edit values
 *
 */
public class EditTable extends Table {
  public static final int ItemEdited= 15007;

  ArrayList editors = new ArrayList();
  EditRowSelectionModel selectModel;
  boolean editing = false;

  public EditTable(int style, TableColumnModel cm) {
    super(style | Style.FOCUSABLE, cm);
  }

  protected void initSelectionModel() {
    if ((style & Style.MULTI) != 0) {
      this.sm = new EditRowSelectionModel(Style.MULTI);
    } else {
      this.sm = new EditRowSelectionModel(Style.SINGLE);
    }

    this.sm.init(this);
    selectModel= (EditRowSelectionModel) this.sm;
  }

  public boolean isEditing() {
    return editing;
  }

  protected void setEditing(boolean tf) {
    editing= tf;
  }

  public void onBaseEvent(BaseEvent be) {
    TableItem item = findItem(be.getTarget());
    if (item != null) {
      item.onBaseEvent(be);
    }
  }

  public void setEditor(int column, Widget editor) {
    selectModel.setEditor(column, editor);
  }

  public Widget getEditor(int column) {
    return selectModel.getEditor(column);
  }

  public void editCurrentRow() {
    EditTableItem item = (EditTableItem) getSelectedItem();
    int row= indexOf(item);
    selectModel.openEdit(row, item);
  }

  /**
   * fires a single ItemEdited event with the whole item in be.item
   */
  public void finishEdit() {
    EditTableItem item = (EditTableItem) selectModel.editItem;
    selectModel.closeEdit();
    BaseEvent be= new BaseEvent();
    be.item= item;
      
    fireEvent(ItemEdited, be);
  }
}
